/**
 * @file main.cpp
 * @brief 主程序入口
 * 
 * 集成所有处理模块，执行完整的图像预处理流水线。
 * 通过 platform.h 支持 PC 和 AURIX 双平台。
 */
#include "platform.h"
#include "image_io.h"
#include "adaptive_crop.h"
#include "resize.h"
#include "otsu.h"
#include "binarize.h"


int main() {
    LOG("Starting image preprocessing pipeline...");
    
    // 1. 加载图像
    unsigned char fullImage[IMAGE_HEIGHT][IMAGE_WIDTH];
    if (!loadGrayPNG(IMAGE_PATH, fullImage)) {
        LOG("Failed to load image");
        return 1;
    }
    
    // 2. 智能裁剪
    int top, bottom;
    adaptiveCrop(fullImage, top, bottom);
    LOG("Cropped to rows [" + std::to_string(top) + ", " + std::to_string(bottom) + "]");
    

    #if ENABLE_CSV_OUTPUT == 1
        // 保存裁剪信息到CSV文件（调试用）
        LOG("Saving crop information for visualization...");
        FILE* crop_fp = fopen("assets/adaptive_crop.csv", "w");
        if (crop_fp) {
            fprintf(crop_fp, "top,bottom\n");
            fprintf(crop_fp, "%d,%d\n", top, bottom);
            fclose(crop_fp);
            LOG("Crop data saved to assets/adaptive_crop.csv");
        } else {
            LOG("Warning: Failed to save crop data");
        }
    #endif
    
    
    // 3. 缩放
    unsigned char scaled[SCALED_HEIGHT][SCALED_WIDTH];
    int newHeight;
    downscaleImage(fullImage, top, bottom, scaled, newHeight);
    LOG("Scaled to: " + std::to_string(newHeight) + "x" + std::to_string(SCALED_WIDTH));
    
    // 4. Otsu 阈值计算
    unsigned char threshold = computeOtsuThreshold(scaled, newHeight, SCALED_WIDTH);
    LOG("Otsu threshold: " + std::to_string(threshold));
    
    // 5. 二值化
    unsigned char binary[SCALED_HEIGHT][SCALED_WIDTH];
    binarizeImage(scaled, binary, newHeight, SCALED_WIDTH, threshold);
    
    // 6. 边线提取（使用追踪式边线测算，替代旧的逐行扫描实现）
    int leftEdge[SCALED_HEIGHT], rightEdge[SCALED_HEIGHT];
    trackEdges(binary, newHeight, SCALED_WIDTH, leftEdge, rightEdge);
    LOG("Track-based edge extraction completed");
    

    #if ENABLE_CSV_OUTPUT == 1
    // 保存边线数据到CSV文件（调试用）
    LOG("Saving edge data for visualization...");
    FILE* fp = fopen("assets/edges_debug.csv", "w");
    if (fp) {
        // 输出两套边线数据（追踪结果）以便与旧数据接口一比一替换
        fprintf(fp, "row,leftEdge,rightEdge\n");
        for (int i = 0; i < newHeight; i++) {
            fprintf(fp, "%d,%d,%d\n", i, leftEdge[i], rightEdge[i]);
        }
        fclose(fp);
        LOG("Tracked edge data saved to assets/edges_debug.csv");
    } else {
        LOG("Warning: Failed to save edge data");
    }
    #endif

    
    // 7. 结果处理（平台相关）
    #if CURRENT_PLATFORM == PLATFORM_PC
        if (savePNG("assets/output.png", binary, newHeight, SCALED_WIDTH)) {
            LOG("Result saved to assets/output.png");
        } else {
            LOG("Failed to save result");
        }

    #elif CURRENT_PLATFORM == PLATFORM_AURIX
        // TODO: 实现 AURIX 结果处理（串口发送等）
        // sendBinaryViaUART(binary, newHeight, 320);
        // sendEdgesViaUART(leftEdge, rightEdge, newHeight);
    #endif
        
    LOG("Pipeline finished successfully!");
    return 0;
}